home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5854 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  74 lines

  1. Newsgroups: comp.lang.c
  2. Path: link-1.ts.bcc.ac.uk!reavpar
  3. From: reavpar@ucl.ac.uk (Mr Philip Arthur Riebold)
  4. Subject: Re: How to get a random string each time??
  5. Message-ID: <1996Feb21.150754.81848@ucl.ac.uk>
  6. Date: Wed, 21 Feb 1996 15:07:54 GMT
  7. References: <4fh5od$qq0@news.nevada.edu> <4g4c5m$tlb@news.nevada.edu>
  8. Organization: University College London
  9.  
  10. chancl@nevada.edu (Clapton Chan) writes:
  11.  
  12. >Thanks for all of you kind C gurus.  My problem is solved.
  13. >I did make some stupid code earlier, but hey, everyone gives
  14. >the new guy a break, right?
  15.  
  16. >I now post my solution for your comments.
  17.  
  18. >**************Here*is*the*question*********************
  19.  
  20. >Write a program that reads the list of strings and then selects
  21. >and prints a random string from the list.  
  22.  
  23. >*************Here*is*my*solution***********************
  24.  
  25. >#include <stdio.h>
  26. >#include <string.h>
  27. >#include <stdlib.h>  /* This is where srand and rand is located.*/
  28. > int main ()
  29. > {
  30. >     char *p, str[10][80];
  31. >     int i, j;
  32. >     srand(time(NULL));  /* pseudocode */
  33. >     printf("Enter 10 strings (or '999' to quit):\n");
  34. >     for(i=0; i<10; i++) {
  35. >        fgets(str[i], sizeof(str[i]), stdin);
  36. >        if((p=strchr(str[i], '\n')) != NULL) *p='\0';
  37. >        if(!(strcmp(str[i], "999")))
  38. >           break;
  39. >    }
  40. >    j = rand();
  41. >    j = j%i;  /* this handles early program exit */
  42. >    printf("\nAnswer: %s\n", str[j]);
  43. >    return 1;
  44. > }
  45.  
  46. >*************************End******************************
  47.  
  48. >I hope this program is bug-less.  ;)
  49.  
  50. >Cheers,
  51. >Clapton
  52. >http://www.nevada.edu/home/15/chancl/html/homepage.html
  53.  
  54. Alternatively to save having to buffer each line try this :-
  55.  
  56. int main(void)
  57. {
  58.     char line[BUFSIZ], it[BUFSIZ];
  59.     int n;
  60.     srand48(time(NULL)); /* or seed the generator in some other way */
  61.     for(n = 1; gets(line); n++) /*probably better to use fgets()*/
  62.         if((n * drand48()) < 1.0) /*drand returns a double in [0.0, 1.0) */
  63.             strcpy(it, line);
  64.     puts(it);
  65. }
  66.  
  67. --
  68.     Philip Riebold,
  69.  
  70.